/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.bullionxpress.server.robo;

import com.bullionxpress.server.feed.Feed;
import com.bullionxpress.shared.model.Instrument;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JadaTask extends TimerTask {

    Instrument instrument = null;
    static Connection conn = null;

    public JadaTask(Instrument instrument) {
        this.instrument = instrument;
    }

    public void run() {
        try {
            Connection conn = Jada.getConnection();

            Statement statement = conn.createStatement();
            Statement stmt = conn.createStatement();
            ResultSet r = statement.executeQuery("SELECT * from products");
            HashMap hm = new HashMap();
            Instrument gold = new Instrument("GOLD");
            Instrument silver = new Instrument("SILVER");
            Instrument btc = new Instrument("BTC");
            hm.put(gold.getSymbol(), new Double(Feed.getPriceByInstrument(gold, true)));
            hm.put(silver.getSymbol(), new Double(Feed.getPriceByInstrument(silver, true)));
            hm.put(btc.getSymbol(), new Double(Feed.getPriceByInstrument(btc, true)));

            while (r.next()) {
                try {
                    instrument = new Instrument(r.getString("instrument"));
                    double gp = (Double)hm.get(instrument.getSymbol()); // this needs to be migrated when silver gets added as an instrument.
                    
                    
                    double paypal = r.getDouble("pp");          //0.03;
                    double premium = r.getDouble("premium");    //20
                    double shipping = r.getDouble("shipping");  //18.99
                    double profit = r.getDouble("profit");      //0.03
                    double grams = r.getDouble("grams");        //31.1/4;
                    double karats = r.getDouble("karats");      //24;
                    double discount = r.getDouble("discount");
                    double price = gp * (karats / 24) * grams;

                    double c = price * 0.02;//cost;
                    double rawPrice = price;
                    double rp = rawPrice * discount;
                    double p = price * profit;
                    price = price + c + p + premium + shipping;
                    double pp = price * paypal;
                    String itemId = r.getString("item_id");
                    price += pp;

                    price = JadaPriceFormatter.formatPriceSell(price);
                    // create table products ( istrument varchar(32), pp double, premium double, cost double, shipping double, profit double, grams double, karats double);
                    // insert into products values ('GOLD', 0.03, 20.00, 0.02, 18.99, 0.02, 31, 24);
                    java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());

                    // Apply floor / cieling rules.
                    try { 
                        double floor = 0;
                        double ceiling = 0;
                        floor = r.getDouble("floor");
                        ceiling = r.getDouble("ceiling");
                        
                        if( floor != -1 ){
                            if( price < floor ){
                                price = floor;
                            }                            
                        }
                        if( ceiling != -1 ){
                            if( price > ceiling ){
                                price = ceiling;
                            }
                        }
                        
                    } catch(Exception ex) { 
                        
                    }
                    
                    stmt.executeUpdate("update item_price_search set item_price = " + price + ", rec_update_datetime = '" + ts + "' WHERE item_id = '" + itemId + "'");
                    stmt.executeUpdate("update item set item_cost = " + price + " WHERE item_id = '" + itemId + "'");
                    stmt.executeUpdate("update products set cost = " + rp + " WHERE item_id = '" + itemId + "'");
                    stmt.executeUpdate("update item_price_currency set item_price = " + price + " WHERE item_id = '" + itemId + "'");
                } catch(Exception ex){
                    Logger.getLogger(JadaTask.class.getName()).log(Level.SEVERE, null, ex);
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(JadaTask.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

    }
}